package com.dongdong.service.impl;


import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.dongdong.service.OSSService;
import com.dongdong.utils.Result;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class OSSServiceImpl implements OSSService {

    @Override
    public Result uploadFile(MultipartFile img) {
        String first = "https://";
        String end = "oss-cn-shanghai.aliyuncs.com";
        String endpoint = first+end;
        String bucketName = "xhuihui";
        String filename = img.getOriginalFilename();
        String objectName = new SimpleDateFormat("yyyy/MM/dd").format(new Date())+"/"+
                            UUID.randomUUID().toString()+filename.substring(filename.lastIndexOf("."));

        String accessKey = "LTAI5tLbB9Z4uoPkZKW8Mxx6";
        String secret = "li2XBMbDWYRcCRzxYWcnRQQdqFF0vW";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey,secret);

        try {
            InputStream inputStream = img.getInputStream();
            ossClient.putObject(bucketName, objectName, inputStream);
        } catch (OSSException oe) {
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException ie) {
            System.out.println("Error Message:" + ie.getMessage());

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

//        https://xhuihui.oss-cn-shanghai.aliyuncs.com/2022/07/05/b4d0%BF%A1%E5%9B%BE%E7%89%87_20220514174146.jpg
        String url = first+bucketName+"."+end+"/"+objectName;

        return Result.OK().setData(url);
    }
}
